package com.example.gfsquadwebviewproject.presenter.update;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.example.gfsquadwebviewproject.bean.update.VersionBean;
import com.example.gfsquadwebviewproject.data.ConfigData;
import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.dialog.update.UpdateDialog;
import com.example.gfsquadwebviewproject.dialog.update.UpdateDialogBuilder;
import com.example.gfsquadwebviewproject.installerlibrary.AutoInstaller;
import com.example.gfsquadwebviewproject.m_enum.GlobalHodler;
import com.example.gfsquadwebviewproject.m_enum.GlobalObject;
import com.example.gfsquadwebviewproject.presenter.http.get.IGet;
import com.example.gfsquadwebviewproject.presenter.http.get.IGetRequest;
import com.example.gfsquadwebviewproject.presenter.http.get.OkhttpGet;
import com.example.gfsquadwebviewproject.util.L;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class UpdateAppClassHolder implements IGetRequest {
    String TAG = "UpdateAppClassHolder";

    Context context;
    Constant constant;
    ConfigData configData;

    IGet iGet;
    Gson gson;
    Handler handler;

    UpdateDialog updateDialog;
    static UpdateAppClassHolder updateAppClassHolder;

    AutoInstaller autoInstaller;

    boolean isBusy = false;//是否正在繁忙

    public static UpdateAppClassHolder instance(Context context){
        if (updateAppClassHolder==null){
            updateAppClassHolder = new UpdateAppClassHolder(context);
        }
        return updateAppClassHolder;
    }

    private UpdateAppClassHolder(Context context) {
        this.context = context;
        iGet = new OkhttpGet(this,context);
        gson = new Gson();
        configData = new ConfigData(context);
        handler = new Handler();
        autoInstaller = AutoInstaller.getDefault(context);
    }


    //是否正在繁忙中,即下载中
    public boolean getIsBusy() {
        if (isBusy){
            if (updateDialog!=null && !updateDialog.isShowing() && handler!=null){
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateDialog.show();
                    }
                });
            }
        }
        return isBusy;
    }

    //查询版本信息
    public void compareVersions(){
        try {
            isBusy = true;
            String url = configData.getAddr() + "/api/classbrand/documents/version.txt";
            iGet.get(url, 1);

            GlobalHodler globalHodler = GlobalHodler.instance();
            if (updateDialog!=null){
                updateDialog.dismiss();
                updateDialog = null;
            }
            updateDialog = new UpdateDialogBuilder().buildDialog((Activity)globalHodler.getHashMap(GlobalObject.ACTIVITY));
            updateDialog.setCancelable(false);
        }
        catch (Exception e){
            L.d(TAG,"compareVersions error:"+e);
            isBusy = false;
        }
    }




    public void downloadFile(String url, final float version) {
        L.d(TAG, "download start:"+url);
//        OkHttpClient okHttpClient = new OkHttpClient();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(5 * 60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")//请求结束后关闭
                .addHeader("Accept-Encoding", "identity")
                .build();


        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                e.printStackTrace();
                L.d(TAG,"download failed");
                isBusy = false;

                if (handler!=null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateDialog.setMsg("请求连接失败：" + e);
                            updateDialog.setAccomplish();
                        }
                    });
                }

                if (handler!=null) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (updateDialog!=null && updateDialog.isShowing()) {
                                updateDialog.dismiss();
                            }
                        }
                    },6*1000);
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[10 * 1024];
                int len;
                FileOutputStream fos = null;

                try {
                    String path = Environment.getExternalStorageDirectory().getPath()+"/"+ constant.appName+"_sc";
                    File myDir = new File(path);

                    if (!myDir.exists()) {
                        L.d("Context","创建文件失败:"+path);
                        if (!myDir.mkdirs()) {
                            return;
                        }
                    }
                    final File file = new File(myDir, "app_"+(version+"").replace(".","-")+".apk");

                    is = response.body().byteStream();
                    long total = response.body().contentLength();

                    if (handler!=null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                updateDialog.show();
                                updateDialog.setMaxProgress(100);
                            }
                        });
                    }

                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        final int progress = (int) (sum * 1.0f / total * 100);

                        if (handler!=null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    updateDialog.setProgress(progress);
                                }
                            });
                        }

                    }
                    fos.flush();
                    L.d(TAG,"download success");

                    if (handler!=null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                //自启动
                                updateDialog.setMsg("正在安装" );
                                updateDialog.setAccomplish();
                                autoInstaller.installUseAS(file.getAbsolutePath());
//                                ZtlManager.GetInstance().installAppSilent(file.getAbsolutePath());
                            }
                        });
                    }

                }
                catch (final Exception e) {
                    e.printStackTrace();
                    L.d(TAG,"download error : "+e.getMessage());

                    if (handler!=null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                updateDialog.setMsg("下载失败:"+e);
                            }
                        });
                    }

                    if (handler!=null) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (updateDialog!=null && updateDialog.isShowing()) {
                                    updateDialog.dismiss();
                                }
                            }
                        },6*1000);
                    }
                }
                finally {
                    isBusy = false;
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    //返回更新文档版本号和apk地址
    @Override
    public void requestBackMsg(String msg, int methodType, int requestStatus) {
        L.d(TAG,"requestBackMsg msg:"+msg+"\nrequestStatus="+requestStatus);
        if (requestStatus==1){
            try {
                VersionBean versionBean = gson.fromJson(msg,VersionBean.class);
                float update_version = Float.valueOf(versionBean.getVersion_name());

                PackageManager pm = context.getPackageManager();
                PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
                float current_version = Float.valueOf(packageInfo.versionName.trim());

                if (update_version > current_version) {
                    downloadFile(configData.getAddr() + "/" + versionBean.getApk_url(),update_version);
                }
                else {
                    if (handler!=null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                isBusy = false;
                                Toast.makeText(context, "已是最新版本!", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }
            catch (Exception e){
                isBusy = false;
                L.d(TAG,"requestBackMsg error:"+e);
            }
        }
    }

    public void recycle(){
        try {
            iGet = null;

            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
                handler = null;
            }

            if (updateDialog != null) {
                updateDialog.dismiss();
                updateDialog = null;
            }
            updateAppClassHolder = null;
            isBusy = false;//是否正在繁忙

            autoInstaller = null;
        }
        catch (Exception e){
            Log.d(TAG,"recycle error:"+e);
        }
    }


}
